function M = cell2posArray(MC,date1,date2)
%cell2posArray - Position array from position cell variable
%
%M = cell2posArray(C,date1,date2)
%
% This function extracts the topographical data from the N-by-2 cell variable
% C, where N is the number of targets, C{k,1} is the position matrix of 
% the k-th target and C{k,2} is the corresponding name.
% The input variables date1 and date2 are the initial and final dates of
% the output array, whose data are hourly, i.e. a 24 cpd (cycles per day)
% sampling rate is considered for each target, regardless to the real 
% sampling rate. The dates date1 and date2 are intended in serial date 
% number form. 
% The data related to the k-th target are placed in the matrix M(:,:,k).
% For the targets characterized by sampling rate lower than 24 cpd, the
% positions for which no data are provided are NaN.
%
% See also extraTarget2cell, velArray, selectMeanVelocity. 

% G. Teza, 2018, 2019.

szmc = size(MC);
ns = szmc(1);   % number of stations 

dv = (floor(date1):(1/24):ceil(date2))';    % date vector
nm = length(dv);
M  = nan(nm,4,ns);      % output matrix inizialization
for m = 1:ns
    M(:,1,m) = dv;
end

for k = 1:ns
    strk = MC{k,2};
    Mk = MC{k,1};
    if isempty(Mk)
        fprintf('Data related to station %s unavailable\n',strk);
        continue
    end
    fprintf('Processing of station %s in progress\n',strk);
    tk = Mk(:,1);
    if date1 > tk(1) || date1 < tk(end)
        Itk = (tk >= date1)&(tk <= date2);
        Mk = Mk(Itk,:);
        tk = Mk(:,1);
    end
    nk = size(Mk,1);
    for h = 1:nk
        th = tk(h);
        [~,Ih] = min(abs(dv-th));   % search of the observation time in dh
        M(Ih,2:4,k) = Mk(h,2:4);
    end
end

